package com.jinlia.show.modules.openservice.websocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.utils.StringUtils;
import com.jinlia.show.modules.openservice.entity.ChatMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WebSocketHandler extends AbstractWebSocketHandler {

    @Autowired
    WebSocketService webSocketService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //socket连接成功后触发
        HttpHeaders handshakeHeaders = session.getHandshakeHeaders();
        if (CollectionUtils.isEmpty(handshakeHeaders.get("aa"))) {
            throw new RuntimeException("请登录后");
        }
        log.info("建立websocket连接={}", session.getId());
        WebSocketSessionManager.add(handshakeHeaders.get("aa").get(0), session);
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        // socket连接关闭后触发
        log.info("关闭websocket连接={}", session.getHandshakeHeaders().get("aa").get(0));
        WebSocketSessionManager.removeAndClose(session.getHandshakeHeaders().get("aa").get(0));
    }
}
